package recallin.social.facebook;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import recallin.activities.R;
import recallin.activities.MainActivity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.MultiAutoCompleteTextView;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.android.FacebookError;
import com.facebook.android.Util;

public class Places extends Dialog implements OnItemClickListener {


	private FacebookDialog facebookDialog;

	public Places(Context context, FacebookDialog facebookDialog) {
		super(context);
		this.facebookDialog = facebookDialog;
		this.getWindow().setGravity(Gravity.TOP);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);

	}

	private Handler mHandler;
	private JSONObject location;

	protected ListView placesList;
	protected LocationManager lm;
	protected MyLocationListener locationListener;

	protected static JSONArray jsonArray;
	public final static double TIMES_SQUARE_LAT = 57.706967;
	public final static double TIMES_SQUARE_LON = 11.936796;

	protected ProgressDialog dialog;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mHandler = new Handler();
		location = new JSONObject();

		setContentView(R.layout.places_list);
		placesList = (ListView) findViewById(R.id.places_list);
		placesList.setEmptyView(findViewById(R.id.places_empty_view2));

		try {
			location.put("latitude", new Double(TIMES_SQUARE_LAT));
			location.put("longitude", new Double(TIMES_SQUARE_LON));
			fetchPlaces();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/*
	 * Fetch nearby places by providing the search type as 'place' within 1000
	 * mtrs of the provided lat & lon
	 */
	private void fetchPlaces() {
		/*
		 * Source tag: fetch_places_tag
		 */
		Bundle params = new Bundle();
		params.putString("type", "place");
		try {
			params.putString("center", location.getString("latitude") + ","
					+ location.getString("longitude"));
		} catch (JSONException e) {
			showToast("No places fetched.");
			return;
		}
		params.putString("distance", "1000");
		Utility.mAsyncRunner.request("search", params,
				new placesRequestListener());
	}

	/*
	 * Callback after places are fetched.
	 */
	public class placesRequestListener extends BaseRequestListener {

		@Override
		public void onComplete(final String response, final Object state) {
			Log.d("Facebook-FbAPIs", "Got response: " + response);
			if (dialog != null)
				dialog.dismiss();

			try {
				jsonArray = new JSONObject(response).getJSONArray("data");
				if (jsonArray == null) {
					showToast("Error: nearby places could not be fetched");
					return;
				}
			} catch (JSONException e) {
				showToast("Error: " + e.getMessage());
				return;
			}
			mHandler.post(new Runnable() {
				@Override
				public void run() {
					placesList.setOnItemClickListener(Places.this);
					placesList.setAdapter(new PlacesListAdapter(getContext()));
				}
			});

		}

		public void onFacebookError(FacebookError error) {
			if (dialog != null)
				dialog.dismiss();
			showToast("Fetch Places Error: " + error.getMessage());
		}
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View v, int position, long arg3) {
		if (!Utility.mFacebook.isSessionValid()) {
			Util.showAlert(getContext(), "Warning", "You must first log in.");
		} else {
			Bundle info = new Bundle();
			info.putInt("position", position);
			hide();
			new CheckinDialog(getContext(), info).show();
		}
	}

	public class placesCheckInListener extends BaseRequestListener {
		@Override
		public void onComplete(final String response, final Object state) {
			showToast("API Response: " + response);
		}

		public void onFacebookError(FacebookError error) {
			if (dialog != null)
				dialog.dismiss();
			showToast("Check-in Error: " + error.getMessage());
		}
	}

	public void showToast(final String msg) {
		mHandler.post(new Runnable() {
			@Override
			public void run() {
				Toast toast = Toast.makeText(getContext(), msg,
						Toast.LENGTH_LONG);
				toast.show();
			}
		});
	}

	/**
	 * Definition of the list adapter
	 */
	public class PlacesListAdapter extends BaseAdapter {
		private LayoutInflater mInflater;
		Places placesList;

		public PlacesListAdapter(Context context) {
			mInflater = LayoutInflater.from(context);
		}

		@Override
		public int getCount() {
			return jsonArray.length();
		}

		@Override
		public Object getItem(int position) {
			return null;
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			JSONObject jsonObject = null;
			try {
				jsonObject = jsonArray.getJSONObject(position);
			} catch (JSONException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			View hView = convertView;
			if (convertView == null) {
				hView = mInflater.inflate(R.layout.place_item, null);
				ViewHolder holder = new ViewHolder();
				holder.name = (TextView) hView.findViewById(R.id.place_name);
				holder.location = (TextView) hView
						.findViewById(R.id.place_location);
				hView.setTag(holder);
			}

			ViewHolder holder = (ViewHolder) hView.getTag();
			try {
				holder.name.setText(jsonObject.getString("name"));
			} catch (JSONException e) {
				holder.name.setText("");
			}
			try {
				String location = jsonObject.getJSONObject("location")
						.getString("street")
						+ ", "
						+ jsonObject.getJSONObject("location")
								.getString("city")
						+ ", "
						+ jsonObject.getJSONObject("location").getString(
								"state");
				holder.location.setText(location);
			} catch (JSONException e) {
				holder.location.setText("");
			}
			return hView;
		}

	}

	class ViewHolder {
		TextView name;
		TextView location;
	}

	class MyLocationListener implements LocationListener {

		@Override
		public void onLocationChanged(Location loc) {
			if (dialog != null)
				dialog.dismiss();
			if (loc != null) {
				try {
					location.put("latitude", new Double(loc.getLatitude()));
					location.put("longitude", new Double(loc.getLongitude()));
				} catch (JSONException e) {
				}
				showToast("Location acquired: "
						+ String.valueOf(loc.getLatitude()) + " "
						+ String.valueOf(loc.getLongitude()));
				lm.removeUpdates(this);
				fetchPlaces();
			}
		}

		@Override
		public void onProviderDisabled(String provider) {
		}

		@Override
		public void onProviderEnabled(String provider) {
		}

		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {
		}
	}

	private class CheckinDialog extends Dialog {

		Bundle info;

		public CheckinDialog(Context context, Bundle info) {
			super(context);
			this.info = info;
			this.getWindow().setGravity(Gravity.TOP);
			this.requestWindowFeature(Window.FEATURE_NO_TITLE);
			try {
				final String name = jsonArray.getJSONObject(
						info.getInt("position")).getString("name");
				final String placeID = jsonArray.getJSONObject(
						info.getInt("position")).getString("id");
				this.setContentView(R.layout.check_in_dialog);
				((TextView) findViewById(R.id.fb_checkin_place_name))
						.setText(name);
				((Button) this
						.findViewById(R.id.fb_checkin_btncheckin))
				.setOnClickListener(new android.view.View.OnClickListener() {
					@Override
					public void onClick(View v) {
						final String message = ((MultiAutoCompleteTextView) CheckinDialog.this
								.findViewById(R.id.fb_checkin_text_field))
								.getText().toString();
						Bundle params = new Bundle();
						params.putString("place", placeID);
						params.putString("message", message);
						params.putString("coordinates", location.toString());
						Utility.mAsyncRunner.request("me/checkins", params,
								"POST", new placesCheckInListener(), null);
					}
				});
				((Button) this
						.findViewById(R.id.fb_checkin_btnback))
						.setOnClickListener(new android.view.View.OnClickListener() {
							@Override
							public void onClick(View v) {
								dismiss();
								Places.this.show();
							}
						});
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		@Override
		protected void onCreate(Bundle savedInstanceState) {
			super.onCreate(savedInstanceState);

		}
		
		@Override
		public void onBackPressed() {
			super.onBackPressed();
			this.dismiss();
			facebookDialog.show();
		}

	}
	
	@Override
	public void onBackPressed() {
		super.onBackPressed();
		this.dismiss();
		facebookDialog.show();
	}
	
	
	
}
